<template>
  <div class="menu-management">
    <div class="page-header">
      <h1 class="page-title">菜单管理</h1>
      <p class="page-desc">管理系统菜单配置和权限设置</p>
    </div>

    <div class="page-content">
      <!-- 菜单预览 -->
      <el-card class="preview-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>菜单预览</span>
            <el-button type="primary" size="small" @click="refreshPreview">
              <el-icon><Refresh /></el-icon>
              刷新预览
            </el-button>
          </div>
        </template>
        
        <div class="preview-container">
          <div class="preview-sidebar">
            <DynamicMenu />
          </div>
          <div class="preview-content">
            <BreadcrumbNav />
            <div class="preview-main">
              <el-empty description="页面内容区域" />
            </div>
          </div>
        </div>
      </el-card>

      <!-- 菜单配置 -->
      <el-card class="config-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>菜单配置</span>
            <div class="header-actions">
              <el-button type="success" size="small" @click="addMenu">
                <el-icon><Plus /></el-icon>
                添加菜单
              </el-button>
              <el-button type="warning" size="small" @click="saveConfig">
                <el-icon><Check /></el-icon>
                保存配置
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="menuConfigData"
          row-key="key"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          style="width: 100%"
        >
          <el-table-column prop="key" label="菜单标识" width="150" />
          <el-table-column prop="label" label="菜单名称" width="150" />
          <el-table-column prop="icon" label="图标" width="100">
            <template #default="{ row }">
              <span v-if="row.icon" class="menu-icon-preview">{{ row.icon }}</span>
              <el-icon v-else><Menu /></el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="路径" width="200" />
          <el-table-column prop="roles" label="角色权限" width="200">
            <template #default="{ row }">
              <el-tag
                v-for="role in row.roles"
                :key="role"
                :type="getRoleTagType(role)"
                size="small"
                style="margin-right: 4px;"
              >
                {{ getRoleLabel(role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="permission" label="权限标识" width="150" />
          <el-table-column prop="order" label="排序" width="80" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="editMenu(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="deleteMenu(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 权限测试 -->
      <el-card class="test-card" shadow="never">
        <template #header>
          <span>权限测试</span>
        </template>

        <div class="test-section">
          <h3>当前用户信息</h3>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="用户类型">
              <el-tag :type="getRoleTagType(currentUserType)">
                {{ getRoleLabel(currentUserType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="权限列表">
              <el-tag
                v-for="permission in currentPermissions"
                :key="permission"
                type="info"
                size="small"
                style="margin-right: 4px;"
              >
                {{ permission }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="可见菜单数">
              {{ visibleMenuCount }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="test-section">
          <h3>角色切换测试</h3>
          <el-radio-group v-model="testUserType" @change="switchTestUser">
            <el-radio-button value="user">普通用户</el-radio-button>
            <el-radio-button value="lawyer">律师</el-radio-button>
            <el-radio-button value="admin">管理员</el-radio-button>
          </el-radio-group>
        </div>

        <div class="test-section">
          <h3>权限测试</h3>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-card shadow="never">
                <template #header>
                  <span>案件管理权限</span>
                </template>
                <div class="permission-test">
                  <p>case:manage: {{ hasPermission('case:manage') ? '✅' : '❌' }}</p>
                  <p>case:create: {{ hasPermission('case:create') ? '✅' : '❌' }}</p>
                  <p>case:analysis: {{ hasPermission('case:analysis') ? '✅' : '❌' }}</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="never">
                <template #header>
                  <span>系统管理权限</span>
                </template>
                <div class="permission-test">
                  <p>system:manage: {{ hasPermission('system:manage') ? '✅' : '❌' }}</p>
                  <p>user:manage: {{ hasPermission('user:manage') ? '✅' : '❌' }}</p>
                  <p>role:manage: {{ hasPermission('role:manage') ? '✅' : '❌' }}</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="never">
                <template #header>
                  <span>律师服务权限</span>
                </template>
                <div class="permission-test">
                  <p>lawyer:center: {{ hasPermission('lawyer:center') ? '✅' : '❌' }}</p>
                  <p>template:view: {{ hasPermission('template:view') ? '✅' : '❌' }}</p>
                  <p>appointment:manage: {{ hasPermission('appointment:manage') ? '✅' : '❌' }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 菜单编辑对话框 -->
    <el-dialog
      v-model="menuDialogVisible"
      :title="isEdit ? '编辑菜单' : '添加菜单'"
      width="600px"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuFormRules"
        label-width="100px"
      >
        <el-form-item label="菜单标识" prop="key">
          <el-input v-model="menuForm.key" placeholder="请输入菜单标识" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="label">
          <el-input v-model="menuForm.label" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标（emoji或图标名称）" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="角色权限" prop="roles">
          <el-checkbox-group v-model="menuForm.roles">
            <el-checkbox label="user">普通用户</el-checkbox>
            <el-checkbox label="lawyer">律师</el-checkbox>
            <el-checkbox label="admin">管理员</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="权限标识" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="menuForm.order" :min="1" :max="999" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMenu">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMenuStore } from '@/stores/menuStore'
import { useUserAuthStore } from '@/stores/userAuth'
import DynamicMenu from '@/components/DynamicMenu.vue'
import BreadcrumbNav from '@/components/BreadcrumbNav.vue'
import {
  Refresh,
  Plus,
  Check,
  Menu,
  Edit,
  Delete
} from '@element-plus/icons-vue'

const menuStore = useMenuStore()
const userAuthStore = useUserAuthStore()

// 响应式数据
const menuConfigData = ref([])
const testUserType = ref('user')
const menuDialogVisible = ref(false)
const isEdit = ref(false)
const menuFormRef = ref(null)

// 菜单表单
const menuForm = ref({
  key: '',
  label: '',
  icon: '',
  path: '',
  roles: [],
  permission: '',
  order: 1
})

// 表单验证规则
const menuFormRules = {
  key: [
    { required: true, message: '请输入菜单标识', trigger: 'blur' },
    { pattern: /^[a-z-]+$/, message: '菜单标识只能包含小写字母和连字符', trigger: 'blur' }
  ],
  label: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色权限', trigger: 'change' }
  ]
}

// 计算属性
const currentUserType = computed(() => userAuthStore.userType)
const currentPermissions = computed(() => userAuthStore.permissions)
const visibleMenuCount = computed(() => menuStore.filteredMenus.length)

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    user: 'info',
    lawyer: 'warning',
    admin: 'danger'
  }
  return typeMap[role] || 'info'
}

// 获取角色标签文本
const getRoleLabel = (role) => {
  const labelMap = {
    user: '普通用户',
    lawyer: '律师',
    admin: '管理员'
  }
  return labelMap[role] || role
}

// 检查权限
const hasPermission = (permission) => {
  return userAuthStore.hasPermission(permission)
}

// 刷新预览
const refreshPreview = async () => {
  await menuStore.initMenuData()
  ElMessage.success('菜单预览已刷新')
}

// 添加菜单
const addMenu = () => {
  isEdit.value = false
  menuForm.value = {
    key: '',
    label: '',
    icon: '',
    path: '',
    roles: [],
    permission: '',
    order: 1
  }
  menuDialogVisible.value = true
}

// 编辑菜单
const editMenu = (row) => {
  isEdit.value = true
  menuForm.value = { ...row }
  menuDialogVisible.value = true
}

// 删除菜单
const deleteMenu = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单"${row.label}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API删除菜单
    ElMessage.success('菜单删除成功')
    refreshPreview()
  } catch (error) {
    // 用户取消删除
  }
}

// 保存菜单
const saveMenu = async () => {
  try {
    await menuFormRef.value.validate()
    
    // 这里应该调用API保存菜单
    ElMessage.success(isEdit.value ? '菜单更新成功' : '菜单添加成功')
    menuDialogVisible.value = false
    refreshPreview()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 保存配置
const saveConfig = () => {
  ElMessage.success('菜单配置已保存')
}

// 切换测试用户
const switchTestUser = () => {
  // 模拟切换用户角色
  const testPermissions = {
    user: ['case:list'],
    lawyer: ['case:manage', 'case:create', 'case:list', 'lawyer:center', 'template:view'],
    admin: ['case:manage', 'case:create', 'case:analysis', 'case:list', 'system:manage', 'user:manage', 'role:manage', 'lawyer:center', 'template:view']
  }
  
  // 更新用户信息（仅用于测试）
  userAuthStore.setUserInfo({
    user_type: testUserType.value,
    permissions: testPermissions[testUserType.value] || []
  })
  
  // 刷新菜单权限
  menuStore.refreshMenuPermissions()
  
  ElMessage.success(`已切换到${getRoleLabel(testUserType.value)}角色`)
}

// 初始化
onMounted(async () => {
  await menuStore.initMenuData()
  menuConfigData.value = [...menuStore.menuData]
})
</script>

<style scoped>
.menu-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-desc {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.page-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.preview-card,
.config-card,
.test-card {
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.preview-container {
  display: flex;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.preview-sidebar {
  width: 280px;
  border-right: 1px solid #e4e7ed;
}

.preview-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.preview-main {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.menu-icon-preview {
  font-size: 16px;
}

.test-section {
  margin-bottom: 24px;
}

.test-section h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.permission-test p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .menu-management {
    padding: 16px;
  }
  
  .preview-container {
    flex-direction: column;
    height: auto;
  }
  
  .preview-sidebar {
    width: 100%;
    height: 300px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }
}
</style> 